package com.itheima.stargraph.config;

import com.itheima.stargraph.api.ComfyuiApi;
import com.itheima.stargraph.handler.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;


@Configuration
public class ComfyuiConfig {
@Value("${comfyuiHost}")
private String comfyuiHost;

    @Bean
    public ComfyuiApi comfyuiApi() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://"+comfyuiHost)
                .client(client)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(ComfyuiApi.class);
    }
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler) {
        WebSocketClient client = new StandardWebSocketClient();
        String url = "ws://"+comfyuiHost+"/ws?clientId=star-graph";
        WebSocketConnectionManager manager = new WebSocketConnectionManager(client,comfyuiMessageHandler,url);
        manager.setAutoStartup(true);
        return manager;
    }
}